package com.tduck.cloud.api.web.controller.form;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.tduck.cloud.common.util.JsonUtils;
import com.tduck.cloud.common.util.RedisUtils;
import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.form.constant.FormRedisConstants;
import com.tduck.cloud.form.util.FormSyncUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import java.lang.reflect.Type;
import java.util.Map;


/**
 * 表单接口
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/form/")
public class FormController {
    @Resource
    private FormSyncUtils formSyncUtils;
    @Resource
    private RedisUtils redisUtils;

    /**
     * 接收webhook的数据
     */
    @PostMapping("/data/sync")
    @PermitAll
    public Result<Boolean> webhookSync(@RequestBody String data) {
        JSONObject jsonObj = JSONUtil.parseObj(data);
        String eventType = jsonObj.getByPath("eventType", String.class);
        if ("form_data_update".equals(eventType)) {
            jsonObj.remove("handleMode");
            jsonObj.remove("eventType");
            jsonObj.remove("eventTime");
            formSyncUtils.updateFirstById(JSONUtil.toBean(jsonObj, Map.class), jsonObj.getStr("formKey"));
        } else if ("form_data_add".equals(eventType)) {
            jsonObj.remove("handleMode");
            jsonObj.remove("eventType");
            jsonObj.remove("eventTime");
            String formKey = jsonObj.getStr("formKey");
            formSyncUtils.insert(JSONUtil.toBean(jsonObj, Map.class), formKey);
            redisUtils.incr(StrUtil.format(FormRedisConstants.FORM_DATA_COUNT, formKey), 1);
        } else if ("form_data_delete".equals(eventType)) {
            String formKey = jsonObj.getStr("formKey");
            formSyncUtils.delete(jsonObj.getLong("id"), formKey);
            redisUtils.decr(StrUtil.format(FormRedisConstants.FORM_DATA_COUNT, formKey), 1);
        }
        return Result.success();
    }

}
